package com.snbc.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date[] dateArray = new Date[9];
        initialize(dateArray);

        for (Date date : insertionSort(dateArray)) {
            System.out.println(sdf.format(date));
        }
    }

    static void initialize(Date[] array) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = sdf.parse("1970-01-01 00:00:00");
        Date end = sdf.parse("2000-12-31 23:59:59");
        long milliSec = end.getTime() - start.getTime();
        for (int i = 0; i < array.length; i++) {
            long randMilliSec = (long) (Math.random() * milliSec + start.getTime());
            array[i] = new Date(randMilliSec);
        }
    }

    static Date[] insertionSort(Date[] array) {
        for (int i = 1; i < array.length; i++) {
            Date key = array[i];
            int j = i - 1;
            while (j >= 0 && dateToInt(array[j]) > dateToInt(key)) {
                array[j + 1] = array[j];
                j = j - 1;
            }
            array[j + 1] = key;
        }
        return array;
    }

    static int dateToInt(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
        String dateStr = sdf.format(date);
        int dateInt = Integer.parseInt(dateStr);
        return dateInt;
    }

}
